package siau.android.base

import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import hhm.android.library.utils.DataStoreUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.first
import java.util.*

class SBaseApplicationLifeCycle : LifecycleObserver, CoroutineScope by MainScope() {
    private val tag = SBaseApplicationLifeCycle::class.simpleName

    companion object {
        var oldTime: Long = 0
        var sumTime: Long = 0
        var httpTime: Long = 0
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate() {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStart() {
        oldTime = Date().time
        async {
            httpTime = DataStoreUtils.readLongFromDataStore(DataStoreUtils.SUM_TIME).first()
            DataStoreUtils.writeLongToDataStore(DataStoreUtils.SUM_TIME, 0)
            sumTime = 0
            Log.d(tag, "onStart-httpTime：$httpTime")
            Log.d(tag, "onStart-oldTime：$oldTime")
            Log.d(tag, "onStart-sumTime：$sumTime")
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume() {
        SBApplication.appForeground.value = true
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() {
        SBApplication.appForeground.value = false
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onStop() {
        val t = Date().time
        sumTime += t - oldTime
        oldTime = t
        async {
            DataStoreUtils.writeLongToDataStore(DataStoreUtils.OLD_TIME, oldTime)
            DataStoreUtils.writeLongToDataStore(DataStoreUtils.SUM_TIME, sumTime)
            Log.d(tag, "onStop-httpTime：$httpTime")
            Log.d(tag, "onStop-oldTime：$oldTime")
            Log.d(tag, "onStop-sumTime：$sumTime")
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    fun onAny() {
    }
}